/**
 * 刷新页面
 * @returns {boolean}
 */
function rePage() {
    window.location.href = window.location.href.replace('#', '');
    return false;
}

/**
 * 返回上一页
 */
function back() {
    window.history.back(-1);
}
/**
 * 跳转页面
 * @param url
 * @returns {boolean}
 * @constructor
 */
function Urlhref(url) {
    window.location.href = url;
    return false;
}
/**
 * 格式化日期框
 */
function formatDate() {
    In('laydate',function(){
        $('.laydate').each(function(){
            laydate.render({elem: this,trigger: 'click'});
        });
        $('.laytime').each(function(){
            laydate.render({elem: this,type:'time',trigger: 'click'});
        });
        $('.laydatetime').each(function(){
            laydate.render({elem: this,type:'datetime',trigger: 'click'});
        });
    })
}
/**
 * Ajax请求
 * @param url 地址
 * @param parm 参数
 * @param callBack 回调方法
 */
function getAjax(url, parm, callBack) {
    In('layer',function(){
        $.ajax({
            type: 'post',
            url: url,
            data: parm,
            cache: false,
            async: false,
            beforeSend: function (data) {
                layer.load(2);
            },
            success: function (data) {
                layer.closeAll();
                callBack(data);
            },
            error: function () {
                layer.closeAll();
                layer.alert('与服务器断开连接！', {icon: 2});
                return false;
            }
        });
    })
}
/**
 * 单条复选框数据
 * @param reVal
 * @returns {boolean}
 * @constructor
 */
function IsOne(reVal) {
    var isOK = true;
    if (reVal == undefined || reVal == "") {
        alert('请选择要操作的数据');
        isOK = false;
    } else if (reVal.split(",").length > 1) {
        alert('对不起，只能选择一条数据');
        isOK = false;
    }
    return isOK;
}
/**
 * 多条复选框数据
 * @param reVal
 * @returns {boolean}
 * @constructor
 */
function IsMore(reVal) {
    var isOK = true;
    if (reVal == undefined || reVal == "") {
        alert('请选择要操作的数据!');
        isOK = false;
    }
    return isOK;
}
/**
 * 弹窗
 * @param title 标题
 * @param content 地址
 * @param width 宽
 * @param height 高
 */
function openDialog(title, content, width, height) {
    In('layer',function(){
        var index = layer.open({
            title: title,
            type: 2,
            area: [width, height],
            content: content
        });
        return index;
    })
}
/**
 * 确认操作
 * @param msg
 * @param url
 * @param params
 */
function doConfirm(msg, url, params,callBack) {
    In.use('layer',function(){
        layer.confirm(msg, {icon: 3, title: '提示消息'}, function (index) {
            layer.close(index);
            getAjax(url, params, function (data) {
                callBack(data);
            });
        });
    })
}
/**
 * 确认操作数据
 * @param obj 对象
 * @param msg 提醒消息
 */
function doAction(obj,callBack) {
    var len=arguments.length;
    var msg = $(obj).data('msg');
    var url = $(obj).data('url');
    var params = $(obj).data('params');
    doConfirm(msg,url,params,function(data){
        if(data.code==1){
            if(len>1){
                callBack(data);
            }else{
                layer.msg(data.msg, {icon: 1, time: 800}, function () {
                    rePage();
                });
            }
        }else{
            layer.alert(data.msg, {icon: 2});
        }
    });
}
/**
 * 美化复选框 依赖iCheck插件
 */
function iCheck(){
    In('icheck',function(){
        $('.i-checks').iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green',
        });
    })
}
/**
 * 提交表单
 */
function ajaxSubForm(formObj,callBack){
    var len=arguments.length;
    In('validform','layer',function(){
        $(formObj).Validform({
            btnSubmit:'.btnSub',
            ajaxPost: true,
            postonce: true,
            tipSweep: true,
            tiptype:function(msg,o,cssctl){
                var objtip=$("#validError");
                cssctl(objtip,o.type);
                objtip.text(msg);
            },
            beforeSubmit:function(curform){ //表单验证通过
                $('#validError').html();
                layer.load(2);
            },
            callback: function (data) {
                layer.closeAll();
                if (data.code == 1) {
                    if(len>1){
                        callBack(data);
                    }else{
                        Urlhref(data.url);
                    }
                }else{
                    $("#validError").removeClass('Validform_loading').addClass('Validform_wrong').html(data.msg);
                }
                return false;
            }
        });
    })
}
/**
 * 单图片上传
 * @param obj
 */
function uploadOnePic(obj,utype,callback,beforeCallback,local) {
    var len=arguments.length;
    In.use('webuploader',function(){
        var uploader_obj = 'uploader_' + obj;
        uploader_obj = WebUploader.create({
            auto: true,
            resize: true,
            duplicate: true,
            swf: '/public/plugins/webuploader/Uploader.swf',
            server: "/plus/uploader/index.html?utype="+utype+"&action=uploadimage&local="+local,
            pick: "#" + obj,
            fileVal: 'upfile',
            accept: {title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/gif,image/jpeg,image/jpg,image/png,image/svg'},
            compress: {width: 800, height: 1600, quality: 80, compressSize: 204800}
        });
        // 当有文件被添加进队列的时候
        uploader_obj.on('beforeFileQueued', function (file) {
            if(len>3){
                return beforeCallback(file);
            }else{
                return true;
            }
        });
        uploader_obj.on('uploadSuccess', function (file, response) {
            if (response.state == 'SUCCESS') {
                callback(response);
            } else {
                alert(response.state);
            }
        });
    })
}
/**
 * 单附件上传
 * @param obj
 */
function uploadOneFile(obj,utype,callback,beforeCallback,local) {
    In.use('webuploader',function(){
        var uploader_obj = 'uploader_' + obj;
        uploader_obj = WebUploader.create({
            auto: true,
            resize: true,
            duplicate: true,
            swf: '/public/plugins/webuploader/Uploader.swf',
            server: "/plus/uploader/index.html?utype="+utype+"&action=uploadfile&local="+local,
            pick: "#" + obj,
            fileVal: 'upfile'
        });
        var len=arguments.length;
        // 当有文件被添加进队列的时候
        uploader_obj.on('beforeFileQueued', function (file) {
            if(len>3){
                return beforeCallback(file);
            }else{
                return true;
            }
        });
        uploader_obj.on('uploadSuccess', function (file, response) {
            if (response.state == 'SUCCESS') {
                callback(response);
            } else {
                alert(response.state);
            }
        });
    })
}

/**
 *
 * 计算商品的阶梯价格
 * @param  goodsPrice 商品价格字符串
 * @param number 商品数量
 * @returns {{simplePrice: number, allPrice: float}} simplePrice:当前单价，allPrice:总价
 */
function formatGoodsPrice(goodsPrice, number) {
    var simplePrice = 0;
    if (goodsPrice.indexOf(':') > 0) {
        var goodsPrice1 = goodsPrice.split(',');
        for (var i = 0; i < goodsPrice1.length; i++) {
            var simple = goodsPrice1[i].split(':');
            if (i === 0) {
                simplePrice = simple[1];
            } else {
                if (parseInt(simple[0]) <= parseInt(number)) {
                    simplePrice = simple[1];
                }
            }
        }
    } else {
        simplePrice = goodsPrice;
    }
    return {simplePrice: simplePrice, totalPrice: (parseInt(number) * parseFloat(simplePrice)).toFixed(2)};
}
/**
 * 添加购物车
 * @param skuId 商品skuid
 * @param number 添加的数量
 */
function addCart(url,skuId,number,callBack) {
    getAjax(url,{sku_id:skuId,number:number},function (res) {
        callBack(res);
    })
}

/**
 * 立即购买商品以及购物车选择后购买商品
 * @param skuIds 商品信息，格式为{[name:skuId,value:number],[name:skuId,value:number]}
 */
function batchAddCart(url,skuIds,callBack) {
    getAjax('/home/Cart/batchAddCart',{sku_ids:skuIds},function (res) {
        callBack(res);
    });
}

/******************************************前端模板页函数************************************************/
/**
 * 商品内页交互
 */
function goodsItem(skulist,isAttr) {
    In.ready('goods-item','goods-sku','layer',function () {
        $('.docart').goodsPlugin({
            'addurl': '/user/cart/addcart.html', //添加购物车地址
            'suborderurl': '/user/cart/orderConfirm.html' //订单购买地址
        });
        if(isAttr==1){
            $('.choose-attrs').skuPlugin({skulist:skulist});
        }
    })
}